package ui;

import cn.hutool.core.util.StrUtil;
import entity.MainJFrame;
import entity.User;
import util.JsonRW;
import util.GUIUtil;
import util.UserManager;
import util.CodeGenerator;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 按下Tab键切换焦点
 */
public class RegisterGUI extends MainJFrame {
    private JTextField usernameTextField;
    private JPasswordField passwordTextField;
    private JPasswordField confirmPasswordTextField;
    private JTextField codeTextField;
    private JLabel codeDisplayLabel;

    private String code;

    // 颜色定义
    private final Color PRIMARY_COLOR = new Color(66, 133, 244);
    private final Color SECONDARY_COLOR = new Color(234, 67, 53);
    private final Color BG_COLOR = new Color(245, 245, 245);
    private final Color TEXT_COLOR = new Color(66, 66, 66);
    private final Color FIELD_BG = new Color(255, 255, 255);
    private final Color FIELD_BORDER = new Color(218, 220, 224);

    public RegisterGUI() {
        super();
        code = CodeGenerator.getCode();
        initTextField();
        initComponents();
        setSize(450, 450);
        setLocationRelativeTo(null);
        setVisible(true);

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_ENTER) {
                    registerVerify();
                }
            }
        });
    }

    public void setTextField(String username, String password, String confirmPassword, String code) {
        usernameTextField.setText(username);
        passwordTextField.setText(password);
        confirmPasswordTextField.setText(confirmPassword);
        codeTextField.setText(code);
    }

    private void initTextField() {
        this.usernameTextField = GUIUtil.createStyledTextField(20, FIELD_BORDER, FIELD_BG);
        this.passwordTextField = GUIUtil.createStyledPasswordField(20, FIELD_BORDER, FIELD_BG);
        this.confirmPasswordTextField = GUIUtil.createStyledPasswordField(20, FIELD_BORDER, FIELD_BG);
        this.codeTextField = GUIUtil.createStyledTextField(20, FIELD_BORDER, FIELD_BG);

        codeTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    registerVerify();
                }
            }
        });
    }

    @Override
    public void initComponents() {
        getContentPane().setBackground(BG_COLOR);
        setLayout(new BorderLayout(0, 10));
        ((JComponent) getContentPane()).setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        setTop();
        setTextFields();
        setButtons();
    }

    private void setTop() {
        JPanel panel = new JPanel();
        panel.setBackground(BG_COLOR);
        JLabel label = GUIUtil.createStyledLabel("用户注册", 24, PRIMARY_COLOR);
        label.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        panel.add(label);
        add(panel, BorderLayout.NORTH);
    }

    private void setButtons() {
        JPanel panel = new JPanel();
        panel.setBackground(BG_COLOR);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));

        JButton finishButton = GUIUtil.createStyledButton("完成注册", PRIMARY_COLOR, 120, 40);
        finishButton.addActionListener(_ -> registerVerify());

        JButton backButton = GUIUtil.createStyledButton("返回登录", SECONDARY_COLOR, 120, 40);
        backButton.addActionListener(_ -> {
            LoginGUI loginGUI = new LoginGUI();
            loginGUI.setTextContent("", "");
            dispose();
        });

        panel.add(finishButton);
        panel.add(backButton);

        add(panel, BorderLayout.SOUTH);
    }

    @SuppressWarnings("all")
    private void setTextFields() {
        JPanel panel = new JPanel();
        panel.setBackground(BG_COLOR);
        panel.setLayout(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 5, 8, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.3;

        // 用户名标签和输入框
        panel.add(createFieldLabel("用户名:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 0.7;
        gbc.gridwidth = 2;
        panel.add(usernameTextField, gbc);

        // 密码标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.3;
        gbc.gridwidth = 1;
        panel.add(createFieldLabel("密码:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 0.7;
        gbc.gridwidth = 2;
        panel.add(passwordTextField, gbc);

        // 确认密码标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.3;
        gbc.gridwidth = 1;
        panel.add(createFieldLabel("确认密码:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 0.7;
        gbc.gridwidth = 2;
        panel.add(confirmPasswordTextField, gbc);

        // 验证码标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.weightx = 0.3;
        gbc.gridwidth = 1;
        panel.add(createFieldLabel("验证码:"), gbc);

        // 验证码输入区域和显示区域
        JPanel codePanel = new JPanel(new BorderLayout(5, 0));
        codePanel.setBackground(BG_COLOR);
        codePanel.add(codeTextField, BorderLayout.CENTER);

        // 创建验证码显示标签，设置大小和样式
        codeDisplayLabel = new JLabel(code, SwingConstants.CENTER);
        codeDisplayLabel.setPreferredSize(new Dimension(80, codeTextField.getPreferredSize().height));
        codeDisplayLabel.setOpaque(true);
        codeDisplayLabel.setBackground(Color.WHITE);
        codeDisplayLabel.setForeground(PRIMARY_COLOR);
        codeDisplayLabel.setFont(new Font("Arial", Font.BOLD, 16));
        codeDisplayLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(FIELD_BORDER, 1),
                BorderFactory.createEmptyBorder(0, 5, 0, 5)
        ));

        // 添加点击刷新验证码功能
        codeDisplayLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                code = CodeGenerator.getCode();
                codeDisplayLabel.setText(code);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                codeDisplayLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
                codeDisplayLabel.setToolTipText("点击刷新验证码");
            }
        });

        codePanel.add(codeDisplayLabel, BorderLayout.EAST);

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.weightx = 0.7;
        gbc.gridwidth = 2;
        panel.add(codePanel, gbc);

        add(panel, BorderLayout.CENTER);
    }

    private void registerVerify() {
        String usernameInput = usernameTextField.getText().toLowerCase();
        String passwordInput = new String(passwordTextField.getPassword());
        String confirmPasswordInput = new String(confirmPasswordTextField.getPassword());
        String codeInput = codeTextField.getText().toLowerCase();

        String regex = "^[a-zA-Z0-9.]+$";
        if (!usernameInput.matches(regex) || !passwordInput.matches(regex)) {
            showErrorDialog("用户名或密码不能含有特殊字符！");
            return;
        }

        if (usernameInput.isEmpty() || passwordInput.isEmpty() || confirmPasswordInput.isEmpty() || codeInput.isEmpty()) {
            showErrorDialog("请完善注册信息！");
            return;
        }

        if (StrUtil.isBlank(usernameInput) || StrUtil.isBlank(passwordInput)) {
            showErrorDialog("用户名或密码不能为含有空字符！");
            return;
        }

        if (UserManager.userExists(usernameInput)) {
            showErrorDialog("用户名已存在！");
            return;
        }

        if (!passwordInput.equals(confirmPasswordInput)) {
            showErrorDialog("两次输入密码不一致！");
            return;
        }

        if (!codeInput.equals(code.toLowerCase())) {
            showErrorDialog("验证码错误！");
            code = CodeGenerator.getCode();
            codeDisplayLabel.setText(code); // 更新验证码显示
            return;
        }

        User user = new User(usernameInput, passwordInput, null, null, null);
        UserManager.saveUserToFile(user);

        JsonRW.saveLastUser(usernameInput);

        JOptionPane.showMessageDialog(this, "注册成功！", "成功", JOptionPane.INFORMATION_MESSAGE);

        LoginGUI loginGUI = new LoginGUI();
        loginGUI.setTextContent(usernameInput, passwordInput);
        dispose();
    }


    // 辅助方法：创建字段标签
    private JLabel createFieldLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        label.setForeground(TEXT_COLOR);
        return label;
    }


    // 辅助方法：显示错误对话框
    private void showErrorDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
}